package com.wyw.function.learning.demo7;

import com.wyw.function.learning.common.WordCounter;
import com.wyw.function.learning.common.WordCounterSpliterator;

import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @Title   Spliterator
 * @Description Spliterator 是Java 8中加入的另一个新接口；这个名字代表“可分迭代器”。用于遍历数据源中的元素，为了并行执行而设计的
 *              自定义Spliterator    一个迭代式字数统计方法
 * @Author Mr Wu yewen.wu.china@gmail.com
 * Update History:
 * Author        Time            Content
 */
public class DemoClient19 {

//    public static void main(String[] args) {
//        String s = "I'm a Chinese, I love here";
//        System.out.println(countWords(s));
//    }
//
//    private static int countWords(String s) {
//        int counter = 0;
//        boolean lastSpace = true;
//        for (char c: s.toCharArray()) {
//            if (Character.isWhitespace(c)) {
//                lastSpace = true;
//            } else {
//                if (lastSpace) {
//                    counter ++;
//                }
//                lastSpace = false;
//            }
//        }
//        return counter;
//    }

    /**
     * 函数式
     */
//    public static void main(String[] args) {
//        String s = "I'm a Chinese, I love here";
//        Stream<Character> stream = IntStream.range(0, s.length()).mapToObj(s::charAt);
//        WordCounter reduce =
//                stream.reduce(
//                        new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine
//                );
//        System.out.println(reduce.getCounter());
//    }

    /**
     * 并行,有bug，因为原始String进行拆分的时候有时会把单词拆分成一个，进而拆分成多个
     */
//    public static void main(String[] args) {
//        String s = "I'm a Chinese, I love here";
//        Stream<Character> stream = IntStream.range(0, s.length()).mapToObj(s::charAt);
//        WordCounter reduce = stream.parallel().reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine);
//        System.out.println(reduce.getCounter());
//    }

    public static void main(String[] args) {
        String s = "I'm a Chinese, I love here";
        WordCounterSpliterator spliterator = new WordCounterSpliterator(s);
        Stream<Character> stream = StreamSupport.stream(spliterator, true);
        System.out.println(countWords(stream.parallel()));
    }

    private static int countWords(Stream<Character> stream) {
        WordCounter wordCounter = stream.reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine);
        return wordCounter.getCounter();
    }

}
